﻿using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using Newtonsoft.Json;
using AjaxChat.BLL;
using AjaxChat.Model;
using System.Collections.Generic;

namespace AjaxChat.WebApp.AjaxPages
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class AjaxChatRequest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (context.Request.Form["_type"] != null)
            {
                switch (context.Request.Form["_type"].ToString())
                {
                    case "GetLastToEnd": GetLastToEnd(context); break;
                    case "SendChatMsg": SendChatMsg(context); break;
                    default: break;
                }
            }
        }

        /// <summary>
        /// 发送一个实体JOSN对象数据
        /// </summary>
        /// <param name="context"></param>
        private void GetLastToEnd(HttpContext context)
        {
            int LastID;
            bool isNum = int.TryParse(context.Request.Form["LastID"].ToString(), out LastID);
            int maxCount = (int)context.Application["maxCount"];
            if (isNum && LastID < maxCount)
            {
                B_chatMsg bcm = new B_chatMsg();
                string whereStr = "msgID > " + LastID.ToString();
                List<chatMsg> ListCM = bcm.GetModelList(whereStr);
                string ResJsonStr = JsonConvert.SerializeObject(ListCM);
                context.Response.Write(ResJsonStr);
            }
            else
            {
                context.Response.Write("[]");
            }
        }

        /// <summary>
        /// 保存一个信息
        /// </summary>
        /// <param name="context"></param>
        private void SendChatMsg(HttpContext context)
        {
            chatMsg cm = new chatMsg();
            cm.msgIP = context.Request.Form["msgIP"].ToString();
            cm.msgName = context.Request.Form["msgName"].ToString();
            cm.msgText = context.Request.Form["msgText"].ToString();
            cm.msgTime = DateTime.Now;
            B_chatMsg bcm = new B_chatMsg();
            int addMsgID = bcm.Add(cm);
            context.Application.Lock();
            context.Application["maxCount"] = addMsgID;
            context.Application.UnLock();
            //cm = bcm.GetModel(addMsgID);
            cm.msgID = addMsgID;
            context.Response.Write(JsonConvert.SerializeObject(cm));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
